package com.itjeffrey.autocode.config;

import com.itjeffrey.autocode.security.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 前端浏览器在http协议下因为安全原因无法直接访问本地文件
 * 后端拦截器中配置对应url访问本地文件，若有相关拦截器则在拦截器中放行
 *
 * @From: Jeffrey
 * @Date: 2020/12/13
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Autowired
    private JwtInterceptor jwtInterceptor;
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private Swagger2Properties swagger2Properties;

    /**
     * 配置静态资源路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/avater/**").addResourceLocations("file:" + System.getProperty("user.dir") +
                "\\src\\main\\resources\\upload\\avater\\");
        //配置swagger2的静态资源路径，不然无法访问swagger2页面，报错No mapping for GET /swagger-ui.html
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 视图控制器
     * @param registry
     */
    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/index.html");
    }

    /**
     * 资源权限拦截器
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(securityProperties.getOpenInterfaces())
                //配置swagger2的放行路径，不然无法访问swagger2页面（空白页）
                .excludePathPatterns(swagger2Properties.getAuthPaths());
    }

}
